package com.polaris.live.popup

import android.content.Context
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.adapter.vip.VipShowAdapter
import com.polaris.live.R
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.databinding.ItemVipShowTitleBinding
import com.polaris.live.databinding.PopupVipPrivilegeBinding
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.UserVipIdentity
import com.polaris.live.resp.back_resp.UserVipLevel
import com.polaris.live.resp.back_resp.UserVipPrivilege
import com.polaris.live.resp.go_resp.UseDressUpBean
import com.polaris.live.resp.go_resp.UserVipColorRequest
import com.polaris.live.utils.VipStyle
import com.polaris.live.utils.VipStyleBean
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.route.RouterUtils
import org.greenrobot.eventbus.EventBus

/**
 * VipPrivilegePopup vip特权
 *
 * @author Created by 天晴 on 2024/12/12/004 17:21
 */
class VipPrivilegePopup(
    context: Context,
    private val isMyVip: Boolean,
    private val index: Int,
    private val mUserVipLevels: UserVipLevel,
    private val updata: (() -> Unit)?,
) : CenterPopupView(context) {

    private lateinit var mBinding: PopupVipPrivilegeBinding

    override fun getImplLayoutId(): Int {
        return R.layout.popup_vip_privilege
    }

    private val mVipStyleBean: VipStyleBean by lazy {
        VipStyle.getVipStyle(mUserVipLevels.level)
    }

    private val mAdapter by lazy { VipShowAdapter(isMyVip, mUserVipLevels.level) }
    override fun onCreate() {
        super.onCreate()
        mBinding = PopupVipPrivilegeBinding.bind(popupImplView)
        initListener()
        initObserver()

        mBinding.viewpager.setPageTransformer { page, position ->
            val scaleFactor = 0.85f // 最小缩放比例
            val minAlpha = 0.5f // 最小透明度

            if (position < -1 || position > 1) {
                page.alpha = minAlpha
                page.scaleY = scaleFactor
            } else {
                val scale = scaleFactor + (1 - scaleFactor) * (1 - Math.abs(position))
                page.scaleY = scale
                page.alpha = minAlpha + (1 - minAlpha) * (1 - Math.abs(position))
            }
        }
        mBinding.viewpager.apply {
            offscreenPageLimit = 3 // 保持屏幕外的页面
            (getChildAt(0) as RecyclerView).apply {
                clipToPadding = false // 页面可以超出父容器
                clipChildren = false // 子项可以超出边界
                setPadding(30.autoDp, 0, 30.autoDp, 0) // 设置两侧的 Padding
            }
        }

        val itemDecoration = object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                outRect.left = 10.autoDp
                outRect.right = 10.autoDp // 右间距
            }
        }
        (mBinding.viewpager.getChildAt(0) as RecyclerView).addItemDecoration(itemDecoration)

        val list =
            mUserVipLevels.identities + if (isMyVip) mUserVipLevels.privileges.filter { it.active } else mUserVipLevels.privileges
        mBinding.viewpager.adapter = mAdapter
        mAdapter.setList(list)
        mBinding.viewpagerTitle.bindViewPager(mBinding.viewpager)
        mBinding.viewpagerTitle.bindChildView<Any> { item ->
            val mBinding = ItemVipShowTitleBinding.inflate(LayoutInflater.from(context), null, false)
            when (item) {
                is UserVipIdentity -> {
                    mBinding.root.setBackgroundResource(mVipStyleBean.vipPreviewbg)
                    Glide.with(context)
                        .load(ImageUtils.imgPath(item.icon))
                        .into(mBinding.itemImg)
                }

                is UserVipPrivilege -> {
                    if (item.active) {
                        mBinding.root.setBackgroundResource(mVipStyleBean.vipPreviewOvalbg)
                    } else {
                        mBinding.root.setBackgroundResource(R.drawable.vip_buy_bg_no_activation)
                        mBinding.itemImg.setColorFilter(ColorUtils.getColor(R.color.b3b3b3))
                    }
                    Glide.with(context)
                        .load(ImageUtils.imgPath(item.icon))
                        .into(mBinding.itemImg)
                }
            }

            mBinding.root
        }
        mBinding.viewpagerTitle.setData(list)
        if (index in list.indices) {
            mBinding.viewpager.setCurrentItem(index, false)
            mBinding.viewpagerTitle.setPosition(index, false)
        }

    }

    private fun initObserver() {
        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.getItem(position)
            val level = mUserVipLevels.level
            when (view.id) {
                R.id.dressing_tv -> {
                    if (item is UserVipIdentity) {
                        item.backpackId?.let {
                            useDressUp(it, AppConst.YES)
                        }
                        item.router?.router?.let {
                            if (it.contains("vipNicknameColorWear")) {
                                useColor(true, level, item, position)
                            } else if (it.contains("vipNicknameColorUnload")) {
                                useColor(false, level, item, position)
                            }
                        }
                    } else if (item is UserVipPrivilege) {
                        item.router?.router?.let {
                            RouterUtils.routerGoto(it)
                        }
                    }

                }
            }
        }
    }

    //使用装饰
    private fun useDressUp(
        backpackId: Long,
        useStatus: Int,
    ) {
        val useDressUp = UseDressUpBean(backpackId, useStatus)
        val activity = ViewUtils.getAliveTopActivity() ?: return
        if (activity is BaseVbActivity<*, *>) {
            activity.mViewModel.requestLoading({ userService.useDressUp(useDressUp) }, {
                ToastGravity.showGravity(com.polaris.live.translation.R.string.successfully_worn)
            }, {
                ToastGravity.showGravity(it.message)
            })
        }

    }

    //使用vip颜色
    private fun useColor(
        install: Boolean,
        vipLevel: Long,
        data: UserVipIdentity,
        position: Int,
    ) {
        val request = UserVipColorRequest(install, vipLevel)
        val activity = ViewUtils.getAliveTopActivity() ?: return
        if (activity is BaseVbActivity<*, *>) {
            activity.mViewModel.request({ userService.useColor(request) }, {
                data.router?.router?.let {
                    if (it.contains("vipNicknameColorWear")) {
                        data.router.router = "vipNicknameColorUnload"
                        ToastGravity.showGravity(com.polaris.live.translation.R.string.successfully_worn)
                    } else if (it.contains("vipNicknameColorUnload")) {
                        data.router.router = "vipNicknameColorWear"
                        ToastGravity.showGravity(com.polaris.live.translation.R.string.uninstall_successfully)
                    }
                    mAdapter.notifyItemChanged(position)
                }
                updata?.invoke()
                EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
            }, {
                ToastGravity.showGravity(it.message)
            })
        }
    }

    private fun initListener() {
        mBinding.closeImg.setOnSingleClickListener {
            dismiss()
        }
    }

    override fun getMaxHeight(): Int {
        return ScreenUtils.getScreenHeight()
    }

    override fun getMaxWidth(): Int {
        return ScreenUtils.getScreenWidth()

    }

    override fun getPopupHeight(): Int {
        return ScreenUtils.getScreenHeight()
    }

    override fun getPopupWidth(): Int {
        return ScreenUtils.getScreenWidth()

    }

    companion object {

        fun show(
            context: Context,
            isMyVip: Boolean,
            index: Int,
            mUserVipLevels: UserVipLevel,
            updata: (() -> Unit)?,
        ) {

            XPopup.Builder(context)
                .isViewMode(false)
                .hasShadowBg(true)
                .hasNavigationBar(false)
                .moveUpToKeyboard(false)
                .navigationBarColor(R.color.color_transparent)
                .isDestroyOnDismiss(true)
                .asCustom(VipPrivilegePopup(context, isMyVip, index, mUserVipLevels, updata))
                .show()
        }
    }
}